<template>
  <div class="profile-container">
    <!-- 顶部状态栏 -->
    <div class="status-bar">
      <span class="status-text">12:00</span>
      <div class="status-icons">
        <span class="icon">📶</span>
        <span class="icon">🔋</span>
      </div>
    </div>

    <!-- 头部区域 -->
    <div class="profile-header">
      <!-- 菜单和分享按钮 -->
      <div class="header-top">
        <button class="menu-btn">☰</button>
        <button class="share-btn">□</button>
      </div>

      <!-- 用户信息 -->
      <div class="user-info">
        <div class="avatar">
          <img src="https://via.placeholder.com/80x80/87CEEB/FFFFFF?text=🐱" alt="用户头像">
        </div>
        <div class="user-name">{{ userInfo.nickname }}</div>
        <div class="user-id">XX号: {{ userInfo.phone || userInfo.id }}</div>
        <div class="user-bio">{{ userInfo.bio || '这个人很懒，什么都没有留下' }}</div>

        <!-- 用户标签 -->
        <div class="user-tags">
          <div class="tag male">♂ 男</div>
          <div class="tag country">中国</div>
          <div class="tag age">23岁</div>
          <div class="tag add">添加标签</div>
        </div>
      </div>

      <!-- 统计数据 -->
      <div class="user-stats">
        <div class="stat-item">
          <div class="stat-number">{{ userInfo.following_count || 698 }}</div>
          <div class="stat-label">关注</div>
        </div>
        <div class="stat-item">
          <div class="stat-number">{{ userInfo.follower_count || 1958 }}</div>
          <div class="stat-label">粉丝</div>
        </div>
        <div class="stat-item">
          <div class="stat-number">{{ userInfo.like_collect_count || 73968 }}</div>
          <div class="stat-label">获赞与收藏</div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="header-actions">
        <button class="action-btn edit">编辑资料</button>
        <button class="action-btn settings">设置更多</button>
        <button class="action-btn verify" @click="$router.push('/real-name')">实名认证</button>
      </div>
    </div>

    <!-- 内容导航 -->
    <div class="content-tabs">
      <div :class="['tab', { active: activeTab === 'notes' }]" @click="switchTab('notes')">
        笔记
      </div>
      <div :class="['tab', { active: activeTab === 'collections' }]" @click="switchTab('collections')">
        收藏
      </div>
      <div :class="['tab', { active: activeTab === 'likes' }]" @click="switchTab('likes')">
        喜欢
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="content-area">
      <!-- 笔记标签页 -->
      <div v-if="activeTab === 'notes'">
        <div v-if="loadingPosts" class="loading-state">
          <div class="spinner"></div>
          <p>加载中...</p>
        </div>
        <div v-else-if="posts.length === 0" class="empty-state">
          <div class="empty-icon">📝</div>
          <div class="empty-dots">
            <span></span><span></span><span></span>
          </div>
          <button class="empty-btn" @click="$router.push('/publish')">去种花</button>
        </div>
        <div v-else class="content-grid">
          <div 
            v-for="item in posts" 
            :key="item.id"
            class="content-card"
            @click="viewDetail(item)"
          >
            <div v-if="item.media_urls && item.media_urls.length > 0" class="content-image">
              <img :src="item.media_urls[0]" :alt="item.title">
              <div v-if="item.media_urls.length > 1" class="image-count">📷 {{ item.media_urls.length }}</div>
            </div>
            <div v-else class="content-image placeholder">
              <div class="placeholder-text">📝</div>
            </div>
            <div class="content-info">
              <h3 class="content-title">{{ item.title || '无标题' }}</h3>
              <div class="content-stats">
                <span>❤️ {{ item.like_count || 0 }}</span>
                <span>💬 {{ item.comment_count || 0 }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 收藏标签页 -->
      <div v-else-if="activeTab === 'collections'">
        <div v-if="loadingCollections" class="loading-state">
          <div class="spinner"></div>
          <p>加载中...</p>
        </div>
        <div v-else-if="collections.length === 0" class="empty-state">
          <div class="empty-icon">⭐</div>
          <div class="empty-dots">
            <span></span><span></span><span></span>
          </div>
          <button class="empty-btn">暂无收藏</button>
        </div>
        <div v-else class="content-grid">
          <div 
            v-for="item in collections" 
            :key="item.id"
            class="content-card"
            @click="viewDetail(item)"
          >
            <div class="card-image" v-if="item.media_urls && item.media_urls.length > 0">
              <img :src="item.media_urls[0]" :alt="item.title">
            </div>
            <div class="card-info">
              <h3 class="card-title">{{ item.title || '无标题' }}</h3>
              <p class="card-content">{{ item.content.substring(0, 30) }}...</p>
              <div class="card-meta">
                <span class="likes">❤️ {{ item.like_count }}</span>
                <span class="collects">⭐ {{ item.collect_count }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 喜欢标签页 -->
      <div v-else>
        <div v-if="loadingLikes" class="loading-state">
          <div class="spinner"></div>
          <p>加载中...</p>
        </div>
        <div v-else-if="likes.length === 0" class="empty-state">
          <div class="empty-icon">👍</div>
          <div class="empty-dots">
            <span></span><span></span><span></span>
          </div>
          <button class="empty-btn">暂无喜欢</button>
        </div>
        <div v-else class="content-grid">
          <div 
            v-for="item in likes" 
            :key="item.id"
            class="content-card"
            @click="viewDetail(item)"
          >
            <div class="card-image" v-if="item.media_urls && item.media_urls.length > 0">
              <img :src="item.media_urls[0]" :alt="item.title">
            </div>
            <div class="card-info">
              <h3 class="card-title">{{ item.title || '无标题' }}</h3>
              <p class="card-content">{{ item.content.substring(0, 30) }}...</p>
              <div class="card-meta">
                <span class="likes">❤️ {{ item.like_count }}</span>
                <span class="collects">⭐ {{ item.collect_count }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部导航栏 -->
    <div class="bottom-nav">
      <div class="nav-item" @click="$router.push('/feed')">
        <span class="nav-icon">🏠</span>
        <span class="nav-label">首页</span>
      </div>
      <div class="nav-item">
        <span class="nav-icon">🛒</span>
        <span class="nav-label">购物</span>
      </div>
      <div class="nav-item highlight" @click="$router.push('/publish')">
        <span class="nav-icon-blue">+</span>
        <span class="nav-label">发布</span>
      </div>
      <div class="nav-item">
        <span class="nav-icon">💬</span>
        <span class="nav-label">消息</span>
      </div>
      <div class="nav-item" @click="$router.push('/customer-service')">
        <span class="nav-icon">🛟</span>
        <span class="nav-label">客服</span>
      </div>
      <div class="nav-item active">
        <span class="nav-icon">👤</span>
        <span class="nav-label">我的</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onActivated, watch } from 'vue'
import { useRouter } from 'vue-router'
import axios from '@/api'

const router = useRouter()

const activeTab = ref('notes')
const userInfo = ref({
  nickname: '新用户',
  phone: '',
  id: 123,
  bio: '',
  following_count: 698,
  follower_count: 1958,
  like_collect_count: 73968
})

const collections = ref([])
const likes = ref([])
const posts = ref([]) // 用户发布的笔记
const loadingCollections = ref(false)
const loadingLikes = ref(false)
const loadingPosts = ref(false)

// 监听标签切换 - 每次切换都重新加载数据
watch(activeTab, async (newTab) => {
  if (newTab === 'notes') {
    await fetchPosts()
  } else if (newTab === 'collections') {
    await fetchCollections()
  } else if (newTab === 'likes') {
    await fetchLikes()
  }
})

onMounted(async () => {
  await fetchUserInfo()
  // 默认加载笔记内容
  if (activeTab.value === 'notes') {
    await fetchPosts()
  } else if (activeTab.value === 'collections') {
    await fetchCollections()
  } else if (activeTab.value === 'likes') {
    await fetchLikes()
  }
  
  // 监听页面可见性变化（从详情页返回时刷新）
  document.addEventListener('visibilitychange', handleVisibilityChange)
})

// 页面激活时刷新数据（从其他页面返回时，如果使用了keep-alive）
onActivated(() => {
  console.log('Profile页面激活，刷新数据')
  if (activeTab.value === 'notes') {
    fetchPosts()
  } else if (activeTab.value === 'collections') {
    fetchCollections()
  } else if (activeTab.value === 'likes') {
    fetchLikes()
  }
})

// 监听路由变化，从详情页返回时刷新
watch(() => router.currentRoute.value.path, (newPath, oldPath) => {
  if (newPath === '/profile' && oldPath && oldPath.startsWith('/content/')) {
    console.log('从详情页返回，刷新数据')
    // 延迟一下确保页面已渲染
    setTimeout(() => {
      if (activeTab.value === 'collections') {
        fetchCollections()
      } else if (activeTab.value === 'likes') {
        fetchLikes()
      }
    }, 300)
  }
}, { immediate: false })

const fetchUserInfo = async () => {
  try {
    const token = localStorage.getItem('token')
    if (!token) {
      console.log('未登录')
      return
    }

    // 这里应该调用后端API获取用户信息
    // const response = await axios.get('/user/profile')
    // userInfo.value = response.data
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

// 获取用户发布的笔记
const fetchPosts = async () => {
  loadingPosts.value = true
  try {
    const token = localStorage.getItem('token')
    if (!token) {
      console.log('未登录')
      posts.value = []
      return
    }

    const response = await axios.get('/content/user/posts', {
      headers: { 'Authorization': `Bearer ${token}` }
    })

    if (response.data.success) {
      posts.value = response.data.data || []
      console.log('笔记列表加载成功，共', posts.value.length, '条')
    } else {
      console.error('获取笔记列表失败:', response.data.message)
      posts.value = []
    }
  } catch (error) {
    console.error('获取笔记列表失败:', error)
    console.error('错误详情:', {
      message: error.message,
      response: error.response?.data,
      status: error.response?.status,
      url: error.config?.url
    })
    if (error.response?.status === 404) {
      console.error('API路由不存在，可能是路由顺序问题')
    }
    posts.value = []
  } finally {
    loadingPosts.value = false
  }
}

// 获取收藏内容
const fetchCollections = async () => {
  loadingCollections.value = true
  try {
    const token = localStorage.getItem('token')
    if (!token) {
      console.log('未登录')
      collections.value = []
      return
    }

    const response = await axios.get('/content/user/collections', {
      headers: { 'Authorization': `Bearer ${token}` }
    })

    if (response.data.success) {
      collections.value = response.data.data || []
      console.log('收藏列表加载成功，共', collections.value.length, '条')
    } else {
      console.error('获取收藏列表失败:', response.data.message)
      collections.value = []
    }
  } catch (error) {
    console.error('获取收藏列表失败:', error)
    console.error('错误详情:', {
      message: error.message,
      response: error.response?.data,
      status: error.response?.status,
      url: error.config?.url
    })
    collections.value = []
    if (error.response?.status === 401) {
      alert('请先登录')
      router.push('/login')
    } else if (error.response?.status === 404) {
      console.warn('API路由不存在，可能是路由顺序问题')
      alert('获取收藏列表失败，请检查后端路由配置')
    } else {
      const errorMsg = error.response?.data?.message || error.message || '未知错误'
      console.error('获取收藏列表错误详情:', errorMsg)
      // 不显示alert，避免打扰用户
    }
  } finally {
    loadingCollections.value = false
  }
}

// 获取点赞内容
const fetchLikes = async () => {
  loadingLikes.value = true
  try {
    const token = localStorage.getItem('token')
    if (!token) {
      console.log('未登录')
      likes.value = []
      return
    }

    const response = await axios.get('/content/user/likes', {
      headers: { 'Authorization': `Bearer ${token}` }
    })

    if (response.data.success) {
      likes.value = response.data.data || []
      console.log('点赞列表加载成功，共', likes.value.length, '条')
    } else {
      console.error('获取点赞列表失败:', response.data.message)
      likes.value = []
    }
  } catch (error) {
    console.error('获取点赞列表失败:', error)
    console.error('错误详情:', {
      message: error.message,
      response: error.response?.data,
      status: error.response?.status,
      url: error.config?.url
    })
    likes.value = []
    if (error.response?.status === 401) {
      alert('请先登录')
      router.push('/login')
    } else if (error.response?.status === 404) {
      console.warn('API路由不存在，可能是路由顺序问题')
      alert('获取点赞列表失败，请检查后端路由配置')
    } else {
      const errorMsg = error.response?.data?.message || error.message || '未知错误'
      console.error('获取点赞列表错误详情:', errorMsg)
      // 不显示alert，避免打扰用户
    }
  } finally {
    loadingLikes.value = false
  }
}

// 切换标签
const switchTab = async (tab) => {
  activeTab.value = tab
  // watch会自动触发数据加载
}

// 查看详情
const viewDetail = (item) => {
  router.push(`/content/${item.id}`)
}

// 页面可见时刷新数据（从详情页返回时）
const handleVisibilityChange = () => {
  if (document.visibilityState === 'visible') {
    // 延迟一下，确保页面完全可见
    setTimeout(() => {
      if (activeTab.value === 'collections') {
        fetchCollections()
      } else if (activeTab.value === 'likes') {
        fetchLikes()
      }
    }, 200)
  }
}
</script>

<style scoped>
.profile-container {
  width: 100vw;
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 70px;
}

/* 状态栏 */
.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 15px;
  background: #20b2aa;
  color: white;
  font-size: 12px;
}

.status-icons {
  display: flex;
  gap: 5px;
}

/* 头部区域 */
.profile-header {
  background: linear-gradient(180deg, #20b2aa 0%, #17a69d 100%);
  padding: 20px 15px;
  color: white;
}

.header-top {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.menu-btn, .share-btn {
  background: none;
  border: none;
  color: white;
  font-size: 20px;
  cursor: pointer;
  padding: 5px;
}

.user-info {
  text-align: center;
}

.avatar img {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  border: 3px solid white;
  margin-bottom: 10px;
}

.user-name {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 5px;
}

.user-id {
  font-size: 12px;
  opacity: 0.8;
  margin-bottom: 8px;
}

.user-bio {
  font-size: 14px;
  opacity: 0.9;
  margin-bottom: 15px;
}

.user-tags {
  display: flex;
  justify-content: center;
  gap: 8px;
  flex-wrap: wrap;
  margin-bottom: 15px;
}

.tag {
  background: rgba(255, 255, 255, 0.2);
  padding: 4px 12px;
  border-radius: 15px;
  font-size: 12px;
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.tag.male {
  background: rgba(70, 130, 180, 0.8);
}

.tag.country {
  background: rgba(220, 20, 60, 0.8);
}

.tag.age {
  background: rgba(255, 255, 255, 0.2);
}

.tag.add {
  background: rgba(255, 255, 255, 0.15);
  color: rgba(255, 255, 255, 0.7);
}

/* 统计数据 */
.user-stats {
  display: flex;
  justify-content: space-around;
  margin: 20px 0;
  padding: 15px 0;
  border-top: 1px solid rgba(255, 255, 255, 0.2);
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
}

.stat-item {
  text-align: center;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 12px;
  opacity: 0.8;
}

/* 操作按钮 */
.header-actions {
  display: flex;
  gap: 10px;
  margin-top: 15px;
}

.action-btn {
  flex: 1;
  padding: 10px;
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 20px;
  background: rgba(255, 255, 255, 0.15);
  color: white;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.action-btn:hover {
  background: rgba(255, 255, 255, 0.25);
}

/* 内容导航 */
.content-tabs {
  background: white;
  display: flex;
  border-bottom: 1px solid #f0f0f0;
}

.tab {
  flex: 1;
  padding: 15px;
  text-align: center;
  font-size: 16px;
  color: #666;
  cursor: pointer;
  position: relative;
}

.tab.active {
  color: #007AFF;
}

.tab.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 30px;
  height: 3px;
  background: #007AFF;
  border-radius: 2px;
}

/* 内容区域 */
.content-area {
  min-height: 300px;
  background: white;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 20px;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 20px;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #007AFF;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.content-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
  padding: 10px;
}

.content-card {
  background: white;
  border-radius: 10px;
  overflow: hidden;
  cursor: pointer;
  transition: transform 0.2s;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.content-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.15);
}

.card-image {
  width: 100%;
  height: 150px;
  overflow: hidden;
}

.card-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.card-info {
  padding: 10px;
}

.card-title {
  font-size: 14px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.card-content {
  font-size: 12px;
  color: #666;
  margin-bottom: 8px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.card-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #999;
}

.likes, .collects {
  display: flex;
  align-items: center;
  gap: 3px;
}

.empty-icon {
  font-size: 60px;
  margin-bottom: 20px;
  opacity: 0.3;
}

.empty-dots {
  display: flex;
  gap: 8px;
  margin-bottom: 30px;
}

.empty-dots span {
  width: 8px;
  height: 8px;
  background: #ddd;
  border-radius: 50%;
}

.empty-btn {
  padding: 12px 40px;
  background: #007AFF;
  color: white;
  border: none;
  border-radius: 25px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.empty-btn:hover {
  background: #0056b3;
}

/* 底部导航栏 */
.bottom-nav {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 6px 0;
  border-top: 1px solid #f0f0f0;
  z-index: 100;
}

.nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
  font-size: 11px;
  color: #666;
  cursor: pointer;
  position: relative;
  flex: 1;
}

.nav-item.active {
  color: #007AFF;
}

.nav-icon {
  font-size: 18px;
}

.nav-icon-blue {
  width: 36px;
  height: 36px;
  background: #007AFF;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  font-weight: bold;
}

.nav-label {
  font-size: 9px;
}

.highlight .nav-label {
  color: #007AFF;
}
</style>

